package com.simpleplayer.services;

import android.os.Looper;
import android.os.Handler;

public class Timer implements Runnable {
    public static interface Ticker {
        void onTick();
    }

    private final Ticker ticker;
    private final long timeMs;
    private final Handler handler;
    private boolean started;

    public Timer(Ticker ticker, long timeMs) {
        this(ticker, timeMs, Looper.myLooper());
    }

    public Timer(Ticker ticker, long timeMs, Looper looper) {
        this.ticker = ticker;
        this.timeMs = timeMs;
        this.handler = new Handler(looper);
        this.started = false;
    }

    public void start() {
        synchronized(this) {
            started = true;
            handler.removeCallbacks(this);
            handler.post(this);
        }
    }
    public void stop() {
        synchronized(this) {
            started = false;
            handler.removeCallbacks(this);
        }
    }

    @Override
    public void run() {
        this.ticker.onTick();
        synchronized(this) {
            if (started) {
                handler.postDelayed(this, timeMs);
            }
        }
    }
}
